<?php

declare(strict_types=1);

namespace App\Core;

final class Logger
{
    public static function log(string $level, string $message, array $context = []): void
    {
        $root = defined('APP_ROOT') ? APP_ROOT : dirname(__DIR__, 2);
        $dir = $root . '/storage/logs';
        if (!is_dir($dir)) {
            @mkdir($dir, 0777, true);
        }
        $file = $dir . '/app.log';

        // 基础敏感字段屏蔽
        $safe = [];
        foreach ($context as $k => $v) {
            if (is_string($k) && in_array(strtolower($k), ['password', 'password2', '_token'], true)) {
                $safe[$k] = '***';
            } else {
                $safe[$k] = is_scalar($v) ? (string)$v : '[non-scalar]';
            }
        }

        $line = sprintf('[%s] %s: %s', date('Y-m-d H:i:s'), strtoupper($level), self::interpolate($message, $safe));
        @file_put_contents($file, $line . PHP_EOL, FILE_APPEND);
    }

    public static function error(string $message, array $context = []): void
    {
        self::log('error', $message, $context);
    }

    private static function interpolate(string $message, array $context): string
    {
        $replace = [];
        foreach ($context as $key => $val) {
            $replace['{' . $key . '}'] = $val;
        }
        return strtr($message, $replace);
    }
}
